package ArrayQueue;

import java.util.Scanner;

public class CircleArrayQueue {
    public static void main(String[] args) {
        //测试一把
        //创建一个队列
        CircleQueue queue = new CircleQueue(3);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        //输出一个菜单
        while (loop) {
            System.out.println("s(show):显示队列");
            System.out.println("e(exit):退出程序");
            System.out.println("a(add):添加数据到队列");
            System.out.println("g(get):从队列中取出数据");
            System.out.println("h(head):看一下队列头部");
            key = scanner.next().charAt(0);//接受一个字符
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                case 'a':
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队头的数据是%d\n",res);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
            System.out.println("程序退出");
        }
    }
}
class CircleQueue{

    int font;
    int real;
    int ArrMaxsize;
    int[] arr;

    public CircleQueue(int maxSize) {
        ArrMaxsize = maxSize;
        arr = new int[ArrMaxsize];
        font = 0;//指向当前队首
        real = 0;//指向当前队尾的下一个位置
    }
    public boolean isFull(){
        return (real+1)%ArrMaxsize == font;
    }
    public boolean isEmpty(){
        return real == font;
    }
    public void showQueue() {
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i = font; i < font+size(); i++) {
            System.out.printf("arr[%d]=%d\n",i%ArrMaxsize,arr[i%ArrMaxsize]);
        }
    }
    public int size(){
        return (real+ArrMaxsize-font)%ArrMaxsize;
    }
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列已满！！");
            return;
        }
        arr[real] = n;
        real = (real+1)%ArrMaxsize;
    }

    public int getQueue() {
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        int value = arr[font];
        font = (font+1)%ArrMaxsize;
        return value;
    }

    public int headQueue() {
        return arr[font];
    }
}
